package com.utils;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.util.MapUtils;
import com.alibaba.fastjson.JSON;

import com.entity.EIException;
import org.apache.commons.io.FilenameUtils;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 导出工具类
 * Copyright(c)2016-2022, 贵阳巴士快运旅游有限公司
 * 项目名称: 黔爽巴士
 * Author:suxu (zsx317127523@163.com)
 */
public class ExportUtil {
    private static final Logger logger = LoggerFactory.getLogger(ExportUtil.class);

    public static String nowDate(String DATE_FORMAT) {
        SimpleDateFormat dft = new SimpleDateFormat(DATE_FORMAT);
        return dft.format(new Date());
    }
    public static String getWebPath() {
        // 文件分隔符转化为当前系统的格式
        return "/public" + nowDate("yyyy-MM-dd").replace("-", "/") + "/";
//        return getType() + getModelPath() + DateUtil.nowDate(Constants.DATE_FORMAT_DATE).replace("-", "/") + "/";
    }
    public static String nowDateTimeStr() {
        return nowDate("yyyy-MM-dd HH:mm:ss");
    }

    public static String getServerPath() {
        // 文件分隔符转化为当前系统的格式
        return FilenameUtils.separatorsToSystem( "" + getWebPath());
    }
    /**
     * 导出Excel文件
     * @param fileName  文件名
     * @param title     文件标题
     * @param voList    数据列表
     * @param aliasMap  别名Map（别名需要与数据列表的数据对应）
     * @return 返回给前端的文件名（路径+文件名）
     */
    public static String exportExecl(String fileName, String title, List<?> voList, LinkedHashMap<String, String> aliasMap) {
        if (StrUtil.isBlank(fileName)) {
            throw new EIException("文件名不能为空");
        }
        if (StrUtil.isBlank(title)) {
            throw new EIException("标题不能为空");
        }
        if (CollUtil.isEmpty(voList)) {
            throw new EIException("数据列表不能为空");
        }
        if (CollUtil.isEmpty(aliasMap)) {
            throw new EIException("别名map不能为空");
        }

        // 文件名部分
        String newFileName = getWebPath() +  fileName;
        String filePath = getServerPath();

        System.out.println(11111);
        System.out.println(fileName);
        System.out.println(newFileName);
        System.out.println(filePath);
        // 判断是否存在当前目录，不存在则创建
        File file = new File(filePath);
        if (!file.exists()) {
            file.mkdirs();
        }
        fileName = filePath.concat(fileName);


        // 通过工具类创建writer
        ExcelWriter writer = ExcelUtil.getWriter(fileName);
//        ExcelWriter writer = ExcelUtil.getWriter("d:/writeMapTest.xlsx");
        CellStyle headCellStyle = writer.getHeadCellStyle();
        Font font = writer.createFont();
        font.setBold(true);
        headCellStyle.setFont(font);

        //自定义标题别名
        aliasMap.forEach((key, value) -> writer.addHeaderAlias(key, value));
        // 合并单元格后的标题行，使用默认标题样式
        writer.merge(aliasMap.size() - 1, title);
        writer.merge(aliasMap.size() - 1, StrUtil.format("生成时间:{}", nowDateTimeStr()));
        //设置宽度自适应
        writer.setColumnWidth(-1, 22);
        // 一次性写出内容，使用默认样式，强制输出标题
        writer.write(voList, true);
        // 关闭writer，释放内存
        writer.close();

        return newFileName;
    }


    /***
     *
     * @param response
     * @param data
     * @param tClass
     * @param name
     * @param <T>
     * @throws IOException
     */
    public static <T> void writeExcel(HttpServletResponse response, List<T> data, Class tClass, String name) throws IOException {
        try {
            String dateStr = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
            name = name+dateStr;
            //防止下载时中文乱码
            name = new String(name.getBytes("UTF-8"), "ISO-8859-1");
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            //添加这个是防止前端拿不到Content-disposition
            response.setHeader("Content-Disposition", "attachment;filename=" + name+".xlsx");
            response.setHeader("Access-Control-Expose-Headers","Content-disposition");
            // 这里需要设置不关闭流
//            EasyExcel.write(response.getOutputStream(), tClass).autoCloseStream(Boolean.FALSE).sheet(name).registerConverter(new LocalDateConverter()).registerConverter(new LocalDateTimeConverter())
//                    .doWrite(data);
            EasyExcel.write(response.getOutputStream(), tClass).autoCloseStream(Boolean.FALSE).sheet(name)
                    .doWrite(data);
        } catch (Exception e) {
            logger.error("文件导出失败,错误信息{}",e);
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, String> map = MapUtils.newHashMap();
            map.put("status", "failure");
            map.put("message", "下载文件失败" + e.getMessage());
            response.getWriter().println(JSON.toJSONString(map));
        }
    }

}
